from sqlalchemy import create_engine, MetaData, Table, select, func, or_, and_
from sqlalchemy.orm import Session
from fastapi import HTTPException, Depends
from models import UserModel
from datetime import datetime
from schemas.user_schema import UserCreate, userschema, UserInfo


def get_comment(db: Session, id: int):
	return db.query(Comment).filter(UserModel.id == id).first()


def GetUserList(db: Session, dto: userschema):
	username = dto.username
	create_time = dto.create_time
	is_admin = dto.is_admin
	status = dto.status
	pageSize = dto.pageSize
	pageIndex = dto.pageIndex
	skip = (pageIndex - 1) * pageSize
	query = db.query(UserModel)
	if username:
		query = query.filter(
			or_(
				UserModel.username.ilike(username),
				# 可以连续多个模糊搜索
				# UserModel.description.ilike(search_term)
			)
		)
	
	if (create_time):
		query = query.filter(UserModel.create_time >= create_time)
	if is_admin:
		query = query.filter(UserModel.is_admin == is_admin)
	if (status):
		query = query.filter(UserModel.status == status)
	
	# 查询当前页数据
	total = query.count()
	items = query.offset(skip).limit(pageSize).all()
	
	# 转换为字典列表
	# items_list = [dict(zip(items.keys(), item)) for item in items]
	
	# 计算总页数
	total_pages = (total + pageSize - 1) // pageSize
	
	return {
		"data": items,
		"total": total,
		"pageIndex": pageIndex,
		"pageSize": pageSize,
		"totalPages": total_pages
	}



def register_user(db: Session, user: UserCreate):
    # 检查邮箱是否已存在
    if db.query(UserModel).filter(UserModel.email == user.email).first():
        raise HTTPException(status_code=400, detail="邮箱已被注册")
    # 检查用户名是否已存在 real_name 可以重复
    if db.query(UserModel).filter(UserModel.username == user.username).first():
        raise HTTPException(status_code=400, detail="用户已被注册")
    user_data = user.model_dump(exclude={"password"})
    db_user = UserModel(**user_data)
    db_user.set_password(user.password)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user


"""
登录验证
"""
def authenticate_user(db: Session, username: str, password: str):
     user = db.query(UserModel).filter(UserModel.username == username).first()
     if not  user:
	     raise HTTPException(status_code=400, detail="用户不存在")
     
     if not user.check_password(password):
	     raise HTTPException(status_code=400, detail="密码不正确")
     return  user
"""
删除数据
"""
def del_user(db: Session, id: int):
	# 查询要删除的用户
	db_user = db.query(UserModel).filter(UserModel.id == id, UserModel.status != 2).first()
	
	if db_user is None:
		raise HTTPException(status_code=404, detail="item not found")
	
	# 删除用户
	# await db.delete(db_user)
	# 软删除
	db_user.status = 2  # 用数字表示已删除
	db_user.deleted_at = datetime.now()
	db.commit()
	return {"message": "deleted successfully"}


"""
更新数据
"""


def update_user(db: Session, el: UserInfo):
	item = db.query(UserModel).filter(UserModel.id == el.id).first()
	if item is None:
		raise HTTPException(status_code=404, detail="item not found")
	
	update_data = el.dict(exclude_unset=True)

	# 处理密码修改
	if "password" in update_data and update_data["password"]:
		item.set_password(update_data.pop("password"))
	
	# 删除逻辑
	if "status" in update_data:
		item.status = update_data["status"]
		if update_data["status"] == 2:
			item.deleted_at = datetime.now()
		elif update_data["status"] != 2:
			# 恢复软删除逻辑
			item.deleted_at = None
		update_data.pop("status")
	# 其他字段更新
	for field, value in update_data.items():
		setattr(item, field, value)
	db.commit()
	db.refresh(item)
	
	return {"message": "updated successfully", "data": item}
